package com.cti.ftpservice.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.cti.ftpservice.ftp.DateHelper;
import com.cti.ftpservice.ftp.XmlReadHandler;
import com.ctibook.booksystem.ws.FtpFileDownloadViewVo;
import com.ctibook.booksystem.ws.FtpFileUploadInfoViewVo;
import com.ctibook.booksystem.ws.FtpServiceUploadFtpFilesViewVo;
import com.ctibook.booksystem.ws.FtpServiceViewVo;
import com.ctibook.booksystem.ws.FtpServiceWS;
import com.ctibook.booksystem.ws.FtpUploadFileInfoRecordViewVo;
import com.ctibook.booksystem.ws.OnixBookBaseInfoVo;
import com.ctibook.booksystem.ws.OnixXmlFileReadOnixBookBaseInfoVo;

@Component
public class FtpWsManagerUtil {
	

	private static Log logger = LogFactory.getLog(FtpWsManagerUtil.class);
	private static FtpWsManagerUtil ftpWsManagerUtil;
    
	@Autowired
    private  FtpServiceWS ftpServiceWS;
    
    @PostConstruct //@PostConstruct修饰的方法会在服务器加载Servle的时候运行，并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
    public void init() {
    	ftpWsManagerUtil = this;
    	ftpWsManagerUtil.ftpServiceWS = this.ftpServiceWS;
    } 

		@SuppressWarnings("unchecked")
		public static <T>  List<T> convertObjectToModelList(Object obj){
			List<T> vos=new ArrayList<T>();
	        if(obj!=null){
	        	 if (obj instanceof ArrayList<?>){
	        		 vos=(List<T>)obj;
	 	        }else{
	 	        	vos.add((T)obj);
	 	        }
	        }
	        return vos;
		}  

	
	
	/**
	 * 代理调用
	 * @param ftpServiceType
	 * @return
	 */
	public  static List<FtpServiceViewVo> getFtpServiceViewVosByTypeFromProxy(String ftpServiceType) {
		try {
			 
    		 return ftpWsManagerUtil.ftpServiceWS.getFtpServiceViewVosByType(ftpServiceType,1);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}  
        return null;
	}
	
	public static void deleteFtpService(String ftpServiceId) {
		try {
			
			ftpWsManagerUtil.ftpServiceWS.deleteFtpService(ftpServiceId);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}  
	}
	
	public static void  addOrUpdateFtpService(FtpServiceViewVo viewVo) {
		try {
			 
			ftpWsManagerUtil.ftpServiceWS.addOrUpdateFtpService(viewVo);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}  
	}
	
	/**
	 * 
	 * @return
	 */
	public  static List<FtpServiceUploadFtpFilesViewVo> getFtpServiceUploadFtpFileInfo() {
		try {
			 
    		 return ftpWsManagerUtil.ftpServiceWS.getFtpServiceUploadFtpFileInfo();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}  
        return null;
	}
	
	public  static void  addUploadFtpFileRecord(FtpFileUploadInfoViewVo viewVo,String ftpServiceId) {
		try {
			 
			 FtpUploadFileInfoRecordViewVo recordVo=convertFtpServiceUploadFtpFilesViewVoToUploadFtpFileRecord(viewVo);
			 ftpWsManagerUtil.ftpServiceWS.addUploadFtpFileRecord(recordVo,ftpServiceId);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}  
	}
	
	public static FtpUploadFileInfoRecordViewVo convertFtpServiceUploadFtpFilesViewVoToUploadFtpFileRecord(FtpFileUploadInfoViewVo viewVo){
		FtpUploadFileInfoRecordViewVo recordVo=new FtpUploadFileInfoRecordViewVo();
		if(viewVo!=null)
		{
			recordVo.setFtpFileInfoId(viewVo.getId());
			recordVo.setUploaderId(viewVo.getUploaderId());
			recordVo.setUploadFtpServiceId(viewVo.getFtpServiceId());
		}
		return recordVo;
	} 
	
	
	public static List<String> getFtpFileMatchFtpServiceRecordIdsByFtpFileIdAndFtpServiceId(String ftpFileId,String ftpServiceId){
		try {
			 
			 return ftpWsManagerUtil.ftpServiceWS.getFtpFileMatchFtpServiceRecordIdsByFtpFileIdAndFtpServiceId(ftpFileId,ftpServiceId);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
	
	public static void updateFtpFileMatchFtpServiceRecordPassInfo(String recordId,Boolean pass){
		try {
			 
			ftpWsManagerUtil.ftpServiceWS.updateFtpFileMatchFtpServiceRecordPassInfo(recordId,pass);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	
	public static List<FtpFileDownloadViewVo> getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(String ftpServiceId,List<String> downloadPaths){
		try {
			 
			 return ftpWsManagerUtil.ftpServiceWS.getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(ftpServiceId, downloadPaths);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 保存从Onix文件解析的书目数据，如果超过1000条，分批次保存，每次存1000条数据，这样可以防止一直占用服务，导致timeout
	 * alreadySaveRecordCount 上次解析已经保存的记录数
	 * 上次保存一部分数据如果出错，或者和服务断开连接，下次直接从第alreadySaveRecordCount+1条数据进行保存，不用重复保存前面的数据。
	 * @param baseInfoVo
	 */
	public static void saveOnixXmlFileReadOnixBookBaseInfoVo(OnixXmlFileReadOnixBookBaseInfoVo baseInfoVo){
		if(baseInfoVo.getBookBaseInfoVos().size()>1000){
			int count=baseInfoVo.getBookBaseInfoVos().size()/1000;
			if(baseInfoVo.getBookBaseInfoVos().size()%1000>0)
				count+=1;
			int recordIndex=0;
			for (int i = 0; i < count; i++) {
				OnixXmlFileReadOnixBookBaseInfoVo baseInfoVo2=new OnixXmlFileReadOnixBookBaseInfoVo();
				baseInfoVo2.setFileLocalPath(baseInfoVo.getFileLocalPath());
				baseInfoVo2.setFtpfileinfoId(baseInfoVo.getFtpfileinfoId());
				baseInfoVo2.setTotalRecordCount(baseInfoVo.getTotalRecordCount());
				baseInfoVo2.setId(baseInfoVo.getId());
				int maxCount=recordIndex+1000;
				if(maxCount>baseInfoVo.getBookBaseInfoVos().size())
					maxCount=baseInfoVo.getBookBaseInfoVos().size();
				for (int j = recordIndex; j < maxCount; j++) {
					baseInfoVo2.getBookBaseInfoVos().add(baseInfoVo.getBookBaseInfoVos().get(recordIndex));
					recordIndex++;
				}
				ftpWsManagerUtil.ftpServiceWS.saveOnixXmlFileReadOnixBookBaseInfoVo(baseInfoVo2);
				
			}
		}else{
			ftpWsManagerUtil.ftpServiceWS.saveOnixXmlFileReadOnixBookBaseInfoVo(baseInfoVo);
		}
		
	}
	
	/**
	 * 解析EdwardElgarPublishing出版社Onix文件
	 * @param fileinfoId
	 * @param fileLocalPath
	 * @param readySaveRecordCount上次保存一部分数据如果出错，或者和服务断开连接，下次直接从第alreadySaveRecordCount+1条数据进行保存，不用重复保存前面的数据。
	 * @return
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 */
	public static OnixXmlFileReadOnixBookBaseInfoVo getEdwardElgarPublishingOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile(String fileinfoId,String fileLocalPath,int readySaveRecordCount)  {
		OnixXmlFileReadOnixBookBaseInfoVo vo=new OnixXmlFileReadOnixBookBaseInfoVo();
		vo.setFtpfileinfoId(fileinfoId);
		//TODO:/获取本地文件，并解析文件
		if(StringUtils.isEmpty(fileLocalPath))
			return null;
		try {
			SAXReader sax=new SAXReader();
			Document doc= sax.read(fileLocalPath);
		 	Element root=doc.getRootElement();
		 	@SuppressWarnings("unchecked")
			List<Element> products=root.elements("Product");
		 	
		 	if(products!=null){
		 		int totalCount=0; //记录总数
		 		int index=0;
		 		for (Element product : products) {
		 			 //已经解析并保存的数据不用二次解析，解析时间
		 			if(index<readySaveRecordCount){
		 				index++;
		 				totalCount++;
		 				continue;
		 			}else{
		 				OnixBookBaseInfoVo bookinfoVo=new OnixBookBaseInfoVo();
			 			
		 				Element isbnElemet=product.element("RecordReference");
			 			bookinfoVo.setIsbn(isbnElemet.getStringValue());
			 			if(bookinfoVo.getIsbn()==null||bookinfoVo.getIsbn().length()==0)
			 				continue;
			 			
			 			Element seriesElement=product.element("Series");
			 			if(seriesElement!=null){
			 				Element TitleOfSeriesEle=seriesElement.element("TitleOfSeries");
			 				if(TitleOfSeriesEle!=null)
			 					bookinfoVo.setSeriesTitle(TitleOfSeriesEle.getStringValue());
			 			}
			 			
			 			Element titleElement=product.element("Title");
			 			if(titleElement!=null){
			 				Element titleText=titleElement.element("TitleText");
			 				if(titleText!=null)
			 					bookinfoVo.setTitle(titleText.getStringValue());
			 				
			 				Element Subtitle=titleElement.element("Subtitle");
			 				if(Subtitle!=null)
			 					bookinfoVo.setSubTitle(Subtitle.getStringValue());
			 			}
			 			
			 			Element LanguageElement=product.element("Language");
			 			if(LanguageElement!=null){
			 				Element LanguageCode=LanguageElement.element("LanguageCode");
			 				if(LanguageCode!=null)
			 					bookinfoVo.setLanguage(LanguageCode.getStringValue());
			 			}
			 			
			 			Element NumberOfPages=product.element("NumberOfPages");
			 			if(NumberOfPages!=null)
			 				bookinfoVo.setPageSize(NumberOfPages.getStringValue());
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> subjects=product.elements("Subject");
			 			String subjectStr="";
			 			for (Element subject : subjects) {
							Element subjectSchemeIdentifier=subject.element("SubjectSchemeIdentifier");
							String subjectType=getSubjectSchemeIdentifierMean(subjectSchemeIdentifier.getStringValue());
							if(subjectType!=null){
								Element SubjectHeadingText=subject.element("SubjectHeadingText");//SubjectHeadingText
								if(SubjectHeadingText!=null)
									subjectStr+=subjectType+":"+SubjectHeadingText.getStringValue()+";";
							}
						}
			 			//TODO:添加主题
			 			bookinfoVo.setSubject(subjectStr);
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> contributors=product.elements("Contributor");
			 			for (Element contributor : contributors) {
							Element contributorRole=contributor.element("ContributorRole");
							String author="";
							if(contributorRole!=null){
								if(contributorRole.getStringValue().equals("A01")||contributorRole.getStringValue().equals("B01"))
								{
									Element PersonName=contributor.element("PersonName");
									if(PersonName!=null){
										author+=PersonName.getStringValue()+";";
									}
								}	
							}
							bookinfoVo.setAuthor(author);
						}
			 			
			 			Element PublisherElement=product.element("Publisher");
			 			if(PublisherElement!=null){
			 				Element PublisherName=PublisherElement.element("PublisherName");
			 				if(PublisherName!=null)
			 					bookinfoVo.setPublisherName(PublisherName.getStringValue());
			 			}
			 			
			 			Element CityOfPublication=product.element("CityOfPublication");
			 			if(CityOfPublication!=null)
			 				bookinfoVo.setPublishAddress(CityOfPublication.getStringValue());
			 			
			 			Element CountryOfPublication=product.element("CountryOfPublication");
			 			if(CountryOfPublication!=null){
			 				if(bookinfoVo.getPublishAddress()==null)
			 					bookinfoVo.setPublishAddress(CountryOfPublication.getStringValue());
			 				else
			 					bookinfoVo.setPublishAddress(bookinfoVo.getPublishAddress()+CountryOfPublication.getStringValue());
			 			}
			 				
			 			Element PublicationDate=product.element("PublicationDate");
			 			if(PublicationDate!=null){
			 				bookinfoVo.setPublishDate(PublicationDate.getStringValue());
			 				if(PublicationDate.getStringValue().length()>4)
			 					bookinfoVo.setPublishYear(PublicationDate.getStringValue().substring(0,4));
			 			}
			 				
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> Measures=product.elements("Measure");
			 			for (Element measure : Measures) {
							Element MeasureTypeCode=measure.element("MeasureTypeCode");
							if(MeasureTypeCode!=null){
								Element Measurement=measure.element("Measurement");
								Element MeasureUnitCode=measure.element("MeasureUnitCode");
								String dimensions="";
								if(MeasureTypeCode.getStringValue().equals("01"))
									dimensions+="Height:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
								if(MeasureTypeCode.getStringValue().equals("02"))
									dimensions+="Width:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
								bookinfoVo.setDimensions(dimensions);
							}
						}
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> OtherTexts=product.elements("OtherText");
			 			for (Element OtherText : OtherTexts) {
			 				Element TextTypeCode=OtherText.element("TextTypeCode");
							if(TextTypeCode!=null&&TextTypeCode.getStringValue().equals("03")){
								Element describe=OtherText.element("Text");
								if(describe!=null){
									bookinfoVo.setDescription(describe.getStringValue());
									break;
								}
							}
						}
			 			
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> SupplyDetails=product.elements("SupplyDetail");
			 			for (Element SupplyDetail : SupplyDetails) {
			 				Element ProductAvailability=SupplyDetail.element("ProductAvailability");
							if(ProductAvailability!=null&&ProductAvailability.getStringValue().equals("20")){
								Element SupplierName=SupplyDetail.element("SupplierName");
								if(SupplierName!=null){
									//TODO:多个供应商
									bookinfoVo.setSupplyInfo(SupplierName.getStringValue());
								}
								
								Element Price=SupplyDetail.element("Price");
								if(Price!=null){
									Element PriceAmount=Price.element("PriceAmount");
									if(PriceAmount!=null)
										bookinfoVo.setPrice(Double.parseDouble(PriceAmount.getStringValue()));
									
									Element CurrencyCode=Price.element("CurrencyCode");
									if(CurrencyCode!=null)
										bookinfoVo.setCurrency(CurrencyCode.getStringValue());
									
								}
								break;
							}
						}
		 			
		 			vo.getBookBaseInfoVos().add(bookinfoVo);
		 			totalCount++;
		 			index++;
		 		  }	
				}
		 		vo.setTotalRecordCount(totalCount);
		 	}
		} catch (Exception e) {
			logger.error("方法getEdwardElgarPublishingOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile："+e.getCause().toString());
		}
		
		return vo;
	}
	
	/**
	 * 解析DeGruyte出版社Onix文件
	 * @param fileinfoId
	 * @param fileLocalPath
	 * @param readySaveRecordCount上次保存一部分数据如果出错，或者和服务断开连接，下次直接从第alreadySaveRecordCount+1条数据进行保存，不用重复保存前面的数据。
	 * @return
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 */
	public static OnixXmlFileReadOnixBookBaseInfoVo getDeGruyteOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile(String fileinfoId,String fileLocalPath,int readySaveRecordCount)  {
		OnixXmlFileReadOnixBookBaseInfoVo vo=new OnixXmlFileReadOnixBookBaseInfoVo();
		vo.setFtpfileinfoId(fileinfoId);
		//TODO:/获取本地文件，并解析文件
		if(StringUtils.isEmpty(fileLocalPath))
			return null;
		
		try {
			SAXReader sax=new SAXReader();
			Document doc= sax.read(fileLocalPath);
		 	Element root=doc.getRootElement();
		 	@SuppressWarnings("unchecked")
			List<Element> products=root.elements("product");
		 	if(products!=null){
		 		int totalCount=0;
		 		int index=0;
		 		for (Element product : products) {
		 			 //已经解析并保存的数据不用二次解析，解析时间
		 			if(index<readySaveRecordCount){
		 				index++;
		 				totalCount++;
		 				continue;
		 			}else{
			 			OnixBookBaseInfoVo bookinfoVo=new OnixBookBaseInfoVo();
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> productidentifiers=product.elements("productidentifier");
			 			for (Element productidentifier : productidentifiers) {
							Element b221=productidentifier.element("b221");
							if(b221!=null&&b221.getStringValue().equals("15")){
								Element isbnElement=productidentifier.element("b244");
								if(isbnElement!=null){
									bookinfoVo.setIsbn(isbnElement.getStringValue());
									break;
								}	
							}	
						}
			 			
			 			if(bookinfoVo.getIsbn()==null||bookinfoVo.getIsbn().length()==0)
			 				continue;
			 			
			 			Element descriptivedetail=product.element("descriptivedetail");
			 			if(descriptivedetail!=null){
			 				@SuppressWarnings("unchecked")
			 				List<Element> Measures=descriptivedetail.elements("measure");
				 			for (Element measure : Measures) {
								Element MeasureTypeCode=measure.element("x315");
								if(MeasureTypeCode!=null){
									Element Measurement=measure.element("c094");
									Element MeasureUnitCode=measure.element("c095");
									String dimensions="";
									if(MeasureTypeCode.getStringValue().equals("01"))
										dimensions+="Height:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
									if(MeasureTypeCode.getStringValue().equals("02"))
										dimensions+="Width:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
									bookinfoVo.setDimensions(dimensions);
								}
							}
				 			
				 			Element titledetail=descriptivedetail.element("titledetail");
				 			if(titledetail!=null){
				 				Element titleElement=titledetail.element("titleelement");
				 				if(titleElement!=null){
				 					Element titleText=titleElement.element("b203");
				 					if(titleText!=null)
				 						bookinfoVo.setTitle(titleText.getStringValue());
				 					
				 					Element subTitle=titleElement.element("b029");
				 					if(subTitle!=null)
				 						bookinfoVo.setSubTitle(subTitle.getStringValue());
				 				}
				 			}
				 			
				 			@SuppressWarnings("unchecked")
							List<Element> contributors=descriptivedetail.elements("contributor");
				 			if(contributors!=null&&contributors.size()>0){
				 				String author="";
				 				for (Element contributor : contributors) {
									Element b035=contributor.element("b035");
									String contributorType=b035.getStringValue();
									if(contributorType.equals("A01")||contributorType.equals("B01")){
										Element personName=contributor.element("b036");
										author+=personName.getStringValue()+";";
									}
								}
				 				bookinfoVo.setAuthor(author);
				 			}
				 			
				 			Element language=descriptivedetail.element("language");
				 			if(language!=null){
				 				Element languageCode=language.element("b252");
				 				if(languageCode!=null)
				 					bookinfoVo.setLanguage(languageCode.getStringValue());
				 			}
				 			
				 			Element illustrationsNote=descriptivedetail.element("b062");
				 			if(illustrationsNote!=null)
				 			{
				 				//TODO: 图表，插图
				 				bookinfoVo.setIllustration(illustrationsNote.getStringValue());
				 			}
				 			
				 			Element extent=descriptivedetail.element("extent");
				 			if(extent!=null){
				 				Element b218=extent.element("b218");//Extent type
				 				if(b218!=null&&b218.getStringValue().equals("00")){
				 					Element b219=extent.element("b219");
				 					if(b219!=null)
				 						bookinfoVo.setPageSize(b219.getStringValue());
				 				}
				 			}
				 			
				 			
				 			@SuppressWarnings("unchecked")
							List<Element> subjects=descriptivedetail.elements("subject");
				 			if(subjects!=null&&subjects.size()>0){
				 				String subjectStr="";
				 				for (Element subject : subjects) {
									Element b067=subject.element("b067");//SubjectSchemeIdentifier
									String subjectType=getSubjectSchemeIdentifierMean(b067.getStringValue());
									if(subjectType!=null){
										Element SubjectHeadingText=subject.element("b070");//SubjectHeadingText
										if(SubjectHeadingText!=null)
											subjectStr+=subjectType+":"+SubjectHeadingText.getStringValue()+";";
									}
								}
				 				
				 				//TODO:主题：添加主题SubjectSchemeIdentifier字典
				 				bookinfoVo.setSubject(subjectStr);
				 			}
			 			}
			 			
			 			Element collateraldetail=product.element("collateraldetail");
			 			if(collateraldetail!=null){
			 				@SuppressWarnings("unchecked")
							List<Element> textcontents=collateraldetail.elements("textcontent");
			 				if(textcontents!=null&&textcontents.size()>0){
			 					for (Element textcontent : textcontents) {
									Element x426=textcontent.element("x426");//textType
									if(x426!=null&&x426.getStringValue().equals("03"))//Description
									{
										Element describe=textcontent.element("d104");
										if(describe!=null)
											bookinfoVo.setDescription(describe.getStringValue());
									}
								}
			 				}
			 			}
						
			 			
			 			Element publishingdetail=product.element("publishingdetail");
			 			if(publishingdetail!=null){
			 				Element publisher=publishingdetail.element("publisher");
			 				if(publisher!=null){
			 					Element b081=publisher.element("b081");//PublisherName
			 					if(b081!=null)
			 						bookinfoVo.setPublisherName(b081.getStringValue());
			 				}
			 				
			 				Element b209=publishingdetail.element("b209");//CityOfPublication
			 				String publiserAddress="";
			 				if(b209!=null){
			 					publiserAddress+=b209.getStringValue();
			 				}
			 				bookinfoVo.setPublishAddress(publiserAddress);
			 				
			 				Element publishingdate=publishingdetail.element("publishingdate");
			 				if(publishingdate!=null){
			 					Element b306=publishingdate.element("b306");//Date
			 					if(b306!=null){
			 						bookinfoVo.setPublishDate(b306.getStringValue());
			 						bookinfoVo.setPublishYear(b306.getStringValue().substring(0, 4));
			 					}
			 						
			 				}
			 			}
			 			
			 			Element productsupply=product.element("productsupply");
			 			if(productsupply!=null){
			 				@SuppressWarnings("unchecked")
							List<Element> supplydetails=productsupply.elements("supplydetail");
			 				if(supplydetails!=null&&supplydetails.size()>0){
			 					for (Element supplydetail : supplydetails) {
			 						
									Element supply=supplydetail.element("supplier");
									if(supply!=null){
										Element j137=supply.element("j137");//SupplierName
										if(j137!=null)
											bookinfoVo.setSupplyInfo(j137.getStringValue());
									}
									
									Element price=supplydetail.element("price");
									if(price!=null){
										Element j151=price.element("j151");//PriceAmount;
										if(j151!=null)
											bookinfoVo.setPrice(Double.parseDouble(j151.getStringValue()));
										
										Element j152=price.element("j152");//CurrencyCode;
										if(j152!=null)
											bookinfoVo.setCurrency(j152.getStringValue());
									}
									break;
								}
			 				}
			 			}
			 			
			 			vo.getBookBaseInfoVos().add(bookinfoVo);
			 			totalCount++;
		 				index++;
		 			}
		 			

				}
		 		vo.setTotalRecordCount(totalCount);
		 	}
		} catch (Exception e) {
			logger.error("方法getDeGruyteOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile："+e.getCause().toString());
		}
		
		return vo;
	}

	/**
	 * 解析Springer出版社Onix文件
	 * @param fileinfoId
	 * @param fileLocalPath
	 * @param readySaveRecordCount上次保存一部分数据如果出错，或者和服务断开连接，下次直接从第alreadySaveRecordCount+1条数据进行保存，不用重复保存前面的数据。
	 * @return
	 */
	public static OnixXmlFileReadOnixBookBaseInfoVo getSpringerOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile(String fileinfoId,String fileLocalPath,int readySaveRecordCount) {
		
		OnixXmlFileReadOnixBookBaseInfoVo vo=new OnixXmlFileReadOnixBookBaseInfoVo();
		vo.setFtpfileinfoId(fileinfoId);
		//TODO:/获取本地文件，并解析文件
		if(StringUtils.isEmpty(fileLocalPath))
			return null;
		try {
			SAXReader sax=new SAXReader();
			Document doc= sax.read(fileLocalPath);
			Element root=doc.getRootElement();
		 	@SuppressWarnings("unchecked")
			List<Element> products=root.elements("product");
		 	if(products!=null){
		 		int totalCount=0;
		 		int index=0;
		 		for (Element product : products) {
		 			if(index<readySaveRecordCount){
		 				//已经解析并保存的数据不用二次解析，解析时间
		 				totalCount++;
		 				index++;
		 				continue;
		 			}else{
		 				
			 			OnixBookBaseInfoVo bookinfoVo=new OnixBookBaseInfoVo();
			 			
			 			@SuppressWarnings("unchecked")
						List<Element> productidentifiers=product.elements("productidentifier");
			 			for (Element productidentifier : productidentifiers) {
							Element b221=productidentifier.element("b221");
							if(b221!=null&&b221.getStringValue().equals("15")){
								Element isbnElement=productidentifier.element("b244");
								if(isbnElement!=null){
									bookinfoVo.setIsbn(isbnElement.getStringValue());
									break;
								}	
							}
								
						}
			 			
			 			if(bookinfoVo.getIsbn()==null||bookinfoVo.getIsbn().length()==0)
			 				continue;
			 			
			 			Element descriptivedetail=product.element("descriptivedetail");
			 			if(descriptivedetail!=null){
			 				@SuppressWarnings("unchecked")
			 				List<Element> Measures=descriptivedetail.elements("measure");
				 			for (Element measure : Measures) {
								Element MeasureTypeCode=measure.element("x315");
								if(MeasureTypeCode!=null){
									Element Measurement=measure.element("c094");
									Element MeasureUnitCode=measure.element("c095");
									String dimensions="";
									if(MeasureTypeCode.getStringValue().equals("01"))
										dimensions+="Height:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
									if(MeasureTypeCode.getStringValue().equals("02"))
										dimensions+="Width:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
									bookinfoVo.setDimensions(dimensions);
								}
							}
				 			
				 			Element titledetail=descriptivedetail.element("titledetail");
				 			if(titledetail!=null){
				 				Element titleElement=titledetail.element("titleelement");
				 				if(titleElement!=null){
				 					Element titleText=titleElement.element("b203");
				 					if(titleText!=null)
				 						bookinfoVo.setTitle(titleText.getStringValue());
				 					
				 					Element subTitle=titleElement.element("b029");
				 					if(subTitle!=null)
				 						bookinfoVo.setSubTitle(subTitle.getStringValue());
				 				}
				 			}
				 			
				 			@SuppressWarnings("unchecked")
							List<Element> contributors=descriptivedetail.elements("contributor");
				 			if(contributors!=null&&contributors.size()>0){
				 				String author="";
				 				for (Element contributor : contributors) {
									Element b035=contributor.element("b035");
									String contributorType=b035.getStringValue();
									if(contributorType.equals("A01")||contributorType.equals("B01")){
										Element personName=contributor.element("b036");//<PersonName>
										if(personName==null)
											personName=contributor.element("b037");//PersonNameInverted
										if(personName!=null)
											author+=personName.getStringValue()+";";
									}
								}
				 				bookinfoVo.setAuthor(author);
				 			}
				 			
				 			Element language=descriptivedetail.element("language");
				 			if(language!=null){
				 				Element languageCode=language.element("b252");
				 				if(languageCode!=null)
				 					bookinfoVo.setLanguage(languageCode.getStringValue());
				 			}
				 			
				 			Element illustrationsNote=descriptivedetail.element("b062");
				 			if(illustrationsNote!=null)
				 			{
				 				//TODO: 图表，插图
				 				bookinfoVo.setIllustration(illustrationsNote.getStringValue());
				 			}
				 			
				 			Element extent=descriptivedetail.element("extent");
				 			if(extent!=null){
				 				Element b218=extent.element("b218");//Extent type
				 				if(b218!=null&&b218.getStringValue().equals("00")){
				 					Element b219=extent.element("b219");
				 					if(b219!=null)
				 						bookinfoVo.setPageSize(b219.getStringValue());
				 				}
				 			}
				 			
				 			
				 			@SuppressWarnings("unchecked")
							List<Element> subjects=descriptivedetail.elements("subject");
				 			if(subjects!=null&&subjects.size()>0){
				 				String subjectStr="";
				 				for (Element subject : subjects) {
									Element b067=subject.element("b067");//SubjectSchemeIdentifier
									String subjectType=getSubjectSchemeIdentifierMean(b067.getStringValue());
									if(subjectType!=null){
										Element SubjectHeadingText=subject.element("b070");//SubjectHeadingText
										if(SubjectHeadingText!=null)
											subjectStr+=subjectType+":"+SubjectHeadingText.getStringValue()+";";
									}
								}
				 				
				 				//TODO:主题：添加主题SubjectSchemeIdentifier字典
				 				bookinfoVo.setSubject(subjectStr);
				 			}
			 			}
			 			
			 			Element collateraldetail=product.element("collateraldetail");
			 			if(collateraldetail!=null){
			 				@SuppressWarnings("unchecked")
							List<Element> textcontents=collateraldetail.elements("textcontent");
			 				if(textcontents!=null&&textcontents.size()>0){
			 					for (Element textcontent : textcontents) {
									Element x426=textcontent.element("x426");//textType
									if(x426!=null&&x426.getStringValue().equals("03"))//Description
									{
										Element describe=textcontent.element("d104");
										if(describe!=null)
											bookinfoVo.setDescription(describe.getStringValue());
									}
								}
			 				}
			 			}
						
			 			
			 			Element publishingdetail=product.element("publishingdetail");
			 			if(publishingdetail!=null){
			 				Element publisher=publishingdetail.element("publisher");
			 				if(publisher!=null){
			 					Element b081=publisher.element("b081");//PublisherName
			 					if(b081!=null)
			 						bookinfoVo.setPublisherName(b081.getStringValue());
			 				}
			 				
			 				Element b209=publishingdetail.element("b209");//CityOfPublication
			 				String publiserAddress="";
			 				if(b209!=null){
			 					publiserAddress+=b209.getStringValue();
			 				}
			 				bookinfoVo.setPublishAddress(publiserAddress);
			 				
			 				Element publishingdate=publishingdetail.element("publishingdate");
			 				if(publishingdate!=null){
			 					Element b306=publishingdate.element("b306");//Date
			 					if(b306!=null){
			 						bookinfoVo.setPublishDate(b306.getStringValue());
			 						bookinfoVo.setPublishYear(b306.getStringValue().substring(0, 4));
			 					}
			 						
			 				}
			 			}
			 			
			 			Element productsupply=product.element("productsupply");
			 			if(productsupply!=null){
			 				@SuppressWarnings("unchecked")
							List<Element> supplydetails=productsupply.elements("supplydetail");
			 				if(supplydetails!=null&&supplydetails.size()>0){
			 					for (Element supplydetail : supplydetails) {
			 						
									Element supply=supplydetail.element("supplier");
									if(supply!=null){
										Element j137=supply.element("j137");//SupplierName
										if(j137!=null)
											bookinfoVo.setSupplyInfo(j137.getStringValue());
									}
									
									Element price=supplydetail.element("price");
									if(price!=null){
										Element j151=price.element("j151");//PriceAmount;
										if(j151!=null)
											bookinfoVo.setPrice(Double.parseDouble(j151.getStringValue()));
										
										Element j152=price.element("j152");//CurrencyCode;
										if(j152!=null)
											bookinfoVo.setCurrency(j152.getStringValue());
									}
									break;
								}
			 				}
			 			}
			 			
			 			vo.getBookBaseInfoVos().add(bookinfoVo);
			 			totalCount++;
			 			index++;
		 			}
				}
		 		vo.setTotalRecordCount(totalCount);
		 	}
		} catch (Exception e) {
			logger.error("方法getSpringerOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile出错："+e.getCause().toString());
		}
	 	return vo;
	}
	
	/**
	 * 解析PrincetonUniversityPublishing出版社Onix文件
	 * @param fileinfoId
	 * @param fileLocalPath
	 * @param readySaveRecordCount上次保存一部分数据如果出错，或者和服务断开连接，下次直接从第alreadySaveRecordCount+1条数据进行保存，不用重复保存前面的数据。
	 * @return
	 * @throws DocumentException
	 * @throws IOException 
	 */
	public static OnixXmlFileReadOnixBookBaseInfoVo getPrincetonUniversityPublishingOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile(String fileinfoId,String fileLocalPath,int readySaveRecordCount)  {
		OnixXmlFileReadOnixBookBaseInfoVo vo=new OnixXmlFileReadOnixBookBaseInfoVo();
		vo.setFtpfileinfoId(fileinfoId);
		//TODO:/获取本地文件，并解析文件
		if(StringUtils.isEmpty(fileLocalPath))
			return null;
		try {
			File file=new File(fileLocalPath);
			if(!file.exists())
				return null;
			SAXReader sax=new SAXReader();
			sax.setValidation(false);
			Document doc=sax.read(fileLocalPath);
		 	Element root=doc.getRootElement();
		 	@SuppressWarnings("unchecked")
			List<Element> products=root.elements("Product");
		 	
		 	if(products!=null){
		 		int totalCount=0;
		 		int index=0;
		 		for (Element product : products) {
		 			  //已经解析并保存的数据不用二次解析，解析时间
		 				if(index<readySaveRecordCount){
		 					index++;
		 					totalCount++;
		 					continue;
		 				}else{
		 					
		 					OnixBookBaseInfoVo bookinfoVo=new OnixBookBaseInfoVo();
		 		 			
			 				Element isbnElemet=product.element("RecordReference");
				 			bookinfoVo.setIsbn(isbnElemet.getStringValue());
				 			if(bookinfoVo.getIsbn()==null||bookinfoVo.getIsbn().length()==0)
				 				continue;
				 			
				 			Element descriptivedetail=product.element("DescriptiveDetail");
				 			if(descriptivedetail!=null){
				 				@SuppressWarnings("unchecked")
				 				List<Element> Measures=descriptivedetail.elements("Measure");
					 			for (Element measure : Measures) {
									Element MeasureTypeCode=measure.element("MeasureType");
									if(MeasureTypeCode!=null){
										Element Measurement=measure.element("Measurement");
										Element MeasureUnitCode=measure.element("MeasureUnitCode");
										String dimensions="";
										if(MeasureTypeCode.getStringValue().equals("01"))
											dimensions+="Height:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
										if(MeasureTypeCode.getStringValue().equals("02"))
											dimensions+="Width:"+Measurement.getStringValue()+MeasureUnitCode.getStringValue()+";";
										bookinfoVo.setDimensions(dimensions);
									}
								}
					 			
					 			Element titledetail=descriptivedetail.element("TitleDetail");
					 			if(titledetail!=null){
					 				Element titleElement=titledetail.element("TitleElement");
					 				if(titleElement!=null){
					 					Element titleText=titleElement.element("TitleText");
					 					if(titleText!=null)
					 						bookinfoVo.setTitle(titleText.getStringValue());
					 					
					 					Element subTitle=titleElement.element("Subtitle");
					 					if(subTitle!=null)
					 						bookinfoVo.setSubTitle(subTitle.getStringValue());
					 				}
					 			}
					 			
					 			@SuppressWarnings("unchecked")
								List<Element> contributors=descriptivedetail.elements("Contributor");
					 			if(contributors!=null&&contributors.size()>0){
					 				String author="";
					 				for (Element contributor : contributors) {
										Element contributorRole=contributor.element("ContributorRole");
										String contributorType=contributorRole.getStringValue();
										//TODO:作者类别
										if(contributorType.equals("A01")||contributorType.equals("B01")){
											Element personName=contributor.element("PersonName");
											author+=personName.getStringValue()+";";
										}
									}
					 				bookinfoVo.setAuthor(author);
					 			}
					 			
					 			Element language=descriptivedetail.element("Language");
					 			if(language!=null){
					 				Element languageCode=language.element("LanguageCode");
					 				if(languageCode!=null)
					 					bookinfoVo.setLanguage(languageCode.getStringValue());
					 			}
					 			
					 			Element illustrationsNote=descriptivedetail.element("IllustrationsNote");
					 			if(illustrationsNote!=null)
					 			{
					 				//TODO: 图表，插图
					 				bookinfoVo.setIllustration(illustrationsNote.getStringValue());
					 			}
					 			
					 			Element extent=descriptivedetail.element("ExtentUnit");
					 			if(extent!=null){
					 				Element b218=extent.element("ExtentType");//Extent type
					 				if(b218!=null&&b218.getStringValue().equals("00")){
					 					Element ExtentValue=extent.element("ExtentValue");
					 					if(ExtentValue!=null)
					 						bookinfoVo.setPageSize(ExtentValue.getStringValue());
					 				}
					 			}
					 			
					 			
					 			@SuppressWarnings("unchecked")
								List<Element> subjects=descriptivedetail.elements("Subject");
					 			if(subjects!=null&&subjects.size()>0){
					 				String subjectStr="";
					 				for (Element subject : subjects) {
										Element SubjectSchemeIdentifier=subject.element("SubjectSchemeIdentifier");//SubjectSchemeIdentifier
										String subjectType=getSubjectSchemeIdentifierMean(SubjectSchemeIdentifier.getStringValue());
										if(subjectType!=null){
											Element SubjectHeadingText=subject.element("SubjectHeadingText");//SubjectHeadingText
											if(SubjectHeadingText!=null)
												subjectStr+=subjectType+":"+SubjectHeadingText.getStringValue()+";";
										}
									}
					 				
					 				//TODO:主题：添加主题SubjectSchemeIdentifier字典
					 				bookinfoVo.setSubject(subjectStr);
					 			}
				 			}
				 			
				 			Element collateraldetail=product.element("CollateralDetail");
				 			if(collateraldetail!=null){
				 				@SuppressWarnings("unchecked")
								List<Element> textcontents=collateraldetail.elements("TextContent");
				 				if(textcontents!=null&&textcontents.size()>0){
				 					for (Element textcontent : textcontents) {
										Element TextType=textcontent.element("TextType");//textType
										if(TextType!=null&&TextType.getStringValue().equals("03"))//Description
										{
											Element describe=textcontent.element("Text");
											if(describe!=null)
												bookinfoVo.setDescription(describe.getStringValue());
										}
									}
				 				}
				 			}
							
				 			
				 			Element publishingdetail=product.element("PublishingDetail");
				 			if(publishingdetail!=null){
				 				Element publisher=publishingdetail.element("Publisher");
				 				if(publisher!=null){
				 					Element PublisherName=publisher.element("PublisherName");//PublisherName
				 					if(PublisherName!=null)
				 						bookinfoVo.setPublisherName(PublisherName.getStringValue());
				 				}
				 				
				 				Element CityOfPublication=publishingdetail.element("CityOfPublication");//CityOfPublication
				 				String publiserAddress="";
				 				if(CityOfPublication!=null){
				 					publiserAddress+=CityOfPublication.getStringValue();
				 				}
				 				bookinfoVo.setPublishAddress(publiserAddress);
				 				
				 				Element publishingdate=publishingdetail.element("PublishingDate");
				 				if(publishingdate!=null){
				 					Element b306=publishingdate.element("Date");//Date
				 					if(b306!=null){
				 						bookinfoVo.setPublishDate(b306.getStringValue());
				 						bookinfoVo.setPublishYear(b306.getStringValue().substring(0, 4));
				 					}
				 						
				 				}
				 			}
				 			
				 			Element productsupply=product.element("ProductSupply");
				 			if(productsupply!=null){
				 				@SuppressWarnings("unchecked")
								List<Element> supplydetails=productsupply.elements("SupplyDetail");
				 				if(supplydetails!=null&&supplydetails.size()>0){
				 					for (Element supplydetail : supplydetails) {
				 						
										Element supply=supplydetail.element("Supplier");
										if(supply!=null){
											Element SupplierName=supply.element("SupplierName");//SupplierName
											if(SupplierName!=null)
												bookinfoVo.setSupplyInfo(SupplierName.getStringValue());
										}
										
										Element price=supplydetail.element("Price");
										if(price!=null){
											Element PriceAmount=price.element("PriceAmount");//PriceAmount;
											if(PriceAmount!=null)
												bookinfoVo.setPrice(Double.parseDouble(PriceAmount.getStringValue()));
											
											Element CurrencyCode=price.element("CurrencyCode");//CurrencyCode;
											if(CurrencyCode!=null)
												bookinfoVo.setCurrency(CurrencyCode.getStringValue());
										}
										break;
									}
				 				}
				 			}
				 			logger.info("第"+totalCount+"条数据："+bookinfoVo.getIsbn()+"解析成功");
				 			vo.getBookBaseInfoVos().add(bookinfoVo);
				 			totalCount++;
				 			index++;
		 				}
					}
			 		vo.setTotalRecordCount(totalCount);
		 	}
		} catch (Exception e) {
			logger.error("方法：getPrincetonUniversityPublishingOnixXmlFileReadOnixBookBaseInfoVoFromXMLFile："+e.getCause().toString());
		}
		return vo;
	}
	
	public static OnixXmlFileReadOnixBookBaseInfoVo readOnixXmlFileCommonMethod(String fileinfoId,String fileLocalPath,int readySaveRecordCount){
		OnixXmlFileReadOnixBookBaseInfoVo vo=new OnixXmlFileReadOnixBookBaseInfoVo();
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
	        File file = new File(fileLocalPath);
	        file.lastModified();
	        XmlReadHandler readHandler=new XmlReadHandler(readySaveRecordCount,new Date(file.lastModified()));
	        parser.parse(file, readHandler);
	        vo.setFtpfileinfoId(fileinfoId);
	        vo.setTotalRecordCount(readHandler.getTotalCount());
	        for (com.cti.ftpservice.vo.OnixBookBaseInfoVo itemVo : readHandler.getBookBaseInfoVos()) {
	        	OnixBookBaseInfoVo newVo=new OnixBookBaseInfoVo();
	        	BeanUtils.copyProperties(itemVo, newVo);
	        	vo.getBookBaseInfoVos().add(newVo);
			}
		} catch (Exception e) {
			logger.error("方法readOnixXmlFileCommonMethod："+e.getCause().toString());
		}
		return vo;
	}
	public static String getSubjectSchemeIdentifierMean(String subjectSchemeIdentifier){
		if(subjectSchemeIdentifier==null||subjectSchemeIdentifier.length()==0)
			return null;
		switch (subjectSchemeIdentifier) {
		case "03":
			return "LC classification";
		case "04":
			return "LC subject heading";
		case "10":
			return "BISAC Subject Heading";
		case "11":
			return "BISAC Regional theme";
		case "12":
			return "BIC subject category";
		case "20":
			return "Keywords";
		case "24":
			return "Proprietary subject scheme";
		case "26":
			return "Warengruppen- Systematik des deutschen Buchhandels";
		case "93":
			return "Thema subject category";
		case "94":
			return "Thema place qualifier";
		}
		return subjectSchemeIdentifier;
	}
	
}
